<template>
    <div>
        <div style="display:inline-block;width:190px;">
            <Input style="width:180px" v-model="searchvalue" placeholder="请输入字典名称"/>
        </div>
        <Button type="success" @click="searchData" icon="ios-search">搜索</Button>
        <Button  @click="emptySearch" v-bind:style="{width: 75 + 'px' }" type="primary">清空检索</Button>
        <br><br>
        <p slot="title" class="margin-top-10">
            <Button  @click="addTreeElement" style="width:90px;" type="primary">添加</Button>
            <Button  @click="deletTreeElement" style="width:90px;" type="primary">删除</Button>
        </p>
        <Tree :data="data1" @on-select-change="selectNode" width="" ref="treeId"></Tree>
        <Modal v-model="modal2" width="360">
            <p slot="header" style="color:#f60;">
                <Icon type="information-circled"></Icon>
                <span>删除提示</span>
            </p>
            <div style="text-align:center">
                <p style="font-size:18px;">是否删除数据?</p>
            </div>
            <div slot="footer">
                <Button type="error" size="large"  @click="del">删除</Button>
                <Button type="info" size="large" @click="modal2=false">取消</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
import ajax from '../../../../libs/axios.js'
import {
    BUS
} from '@/bus/bus.js'
export default {
    data () {
        return {
            modal2 : false,
            data1: [],
            // 选中的节点的id用于添加或删除等
            selectNodeId: '',
            treeSelectNode: [],
            searchvalue: ''
        }
    },
    computed: {
    },
    props: [],
    created () {
        this.initTree(this.searchData)

        // 监听dictionaryOPerate发送的消息
        BUS.$on('dictionaryOperateComplete', (msg) => {
            console.log('组件收到dictionaryOPerate消息***msg:' + msg + ' 重新去加载字典树')
            if (msg.operaName === 'add') {
                // 给选中的节点树做添加子元素
                this.appendTree(this.treeSelectNode[0], msg.treeId)
                // console.log("-----添加后的data10000---------"+JSON.stringify(this.data1));
            }
            if (msg.operaName === 'update') {
                // 给选中的节点树作修改元素
                console.log('---修改----')
                this.updateTree(msg.treeId)
                // console.log("-----添加后的data---------"+JSON.stringify(this.data1));
            }
        })
    },
    methods: {
        initTree (searchvalue) {
            let url = 'adminapi/dictionary/getDictionaryJsonData.html'
            let data = {
                queryName: this.searchvalue
            }
            ajax.formRes(url, data).then(res => {
                // success
                console.log('**********查询树信息成功******************')
                this.data1 = res.data
                console.log('**********显示树赋值成功******************')
            }).catch(res => {
                // fail
                console.log('有错误信息')
            })
        },
        selectNode (data) {
            // 当节点点击第二次的时候会取消选中
            if (data.length === 0) { // 说明取消选中了
                this.selectNodeId = ''
            } else {
                console.log('获取的节点' + JSON.stringify(data))
                console.log('获取的节点的id：' + data[0].id)
                this.selectNodeId = data[0].id
                console.log('给this.selectNodeId赋值：' + this.selectNodeId)
                this.treeSelectNode = data // 选中节点用来后边添加和修改操作
                let MsgData = {
                    operaName: 'update',
                    treeId: data[0].id
                }
                BUS.$emit('dictionarySelectNode', MsgData)
            }
        },
        addTreeElement () { // 点击添加按钮添加树状节点
            if (this.selectNodeId === '') {
                this.$Message.success('请选择节点')
            } else {
                BUS.$emit('dictionaryWantToAddNode', 'add')
            }
        },
        appendTree (nodes, treeId) {
            const children = nodes.children || []
            let nodeId = treeId
            let url = 'adminapi/dictionary/getDictionaryJsonById.html'
            let data = {
                id: nodeId
            }
            ajax.formRes(url, data).then(res => {
                // success
                children.push(res.data)
                this.sortByKey(children,'sort')
                // children数组排序
                this.$set(nodes, 'children', children)
            }).catch(res => {
                console.log('有错误信息')
                // fail
            })
        },
        updateTree (TreeId) {
            console.log('jinrufangfa ---' + TreeId)
            let url = 'adminapi/dictionary/getDictionaryJsonById.html'
            let data = {
                id: TreeId
            }
            let tree = this.$refs.treeId
            ajax.formRes(url, data).then(res => {
                // success 更新节点
                let selected = tree.getSelectedNodes()[0]
                this.$set(selected, 'title', res.data.title)
                this.$set(selected, 'sort', res.data.sort)
                let pKey = tree.flatState[selected.nodeKey].parent
                let parent = tree.flatState.find(el => el.nodeKey === pKey).node
                let children = parent.children
                console.log('!!!!children')
                console.log(tree)
                this.sortByKey(children,'sort')
                // children数组排序
                this.$set(parent, 'children', children)
            }).catch(res => {
                // fail
                console.log('有错误信息')
            })
        },
        deletTreeElement () { // 删除树状节点
            if (this.selectNodeId === '') {
                this.$Message.success('请选择节点')
            } else if (this.selectNodeId === this.$refs.treeId.data[0].id) {
                // 说明选择的是“字典id”
                this.$Message.success('不能删除跟节点')
            } else {
                this.modal2 = true
            }
        },
        del () {
            let url = 'adminapi/dictionary/deleteDictionaryById.html'
            let data = {
                id: this.selectNodeId,
                userId: window.localStorage.getItem('userId'),
                userName: window.localStorage.getItem('userName')
            }
            ajax.formRes(url, data).then(res => {
                // success 去删除子节点
                this.remove()
                // 通知右侧删除显示信息
                BUS.$emit('dictionaryNodeDeleteComplete', 'deleteComplete')
                // 把选中节点数据置为空
                this.selectNodeId = ''
                // 删除成功提示
                this.modal2 = false
                this.$Message.success('删除成功')
            }).catch(res => {
                // fail
                console.log('有错误信息')
            })
        },
        remove () {
            let tree = this.$refs.treeId
            console.log(tree)
            let selected = tree.getSelectedNodes()[0]
            const pKey = tree.flatState[selected.nodeKey].parent
            const parent = tree.flatState.find(el => el.nodeKey === pKey).node
            const index = parent.children.indexOf(selected)
            console.log(parent)
            console.log('----selected.data----------')
            console.log(selected)
            console.log('----parent----------')
            console.log(parent)
            console.log('index:' + index)
            if (index >= 0) {
                parent.children.splice(index, 1)
            }
        },
        searchData () {
            this.initTree(this.searchData)
        },
        emptySearch () {
            this.searchvalue = ''
            this.initTree(this.searchData)
        },
        // 数组对象方法排序:
        sortByKey (array,key) {
            console.log(array)
            console.log(key)
            return array.sort(function (a,b) {
                var x = a[key]
                var y = b[key]
                return ((x < y) ? -1 : ((x > y) ? 1 : 0))
            })
        }
    }
}
</script>
<style>
   /*  .ivu-tree-title{
        width: 100%;
        height: 100%;
        color: brown;
    } */
</style>
